package dao.impl;

import dao.DeptDao;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import pojo.Dept;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class DeptDaoImpl implements DeptDao {
    @Override
    public List<Dept> findAll() {
        // 引入mybatis-config.xml 配置文件
        String resource = "mybatis-config.xml";
        SqlSession sqlSession = null;
        try {
            InputStream resourceAsStream = Resources.getResourceAsStream(resource);
            // 创建会话工厂对象
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
            // 获取会话对象
            sqlSession = sqlSessionFactory.openSession();
            // 执行查询
            List<Dept> depts = sqlSession.getMapper(DeptDao.class).findAll();
            return depts;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if(sqlSession!=null) {
                sqlSession.close();
                //防止会话工厂创建失败报空指针异常
            }
        }
    }
}
